//'use strict';
var trim=function(str) {
  return str.replace(/(^\s*)|(\s*$)/g,'');
};
var JTE = function() {
  var o = {};
  o.print_prefix = '=';
  o._G = {};
  o.fnPool = {};
  o.clear = function() {
    this._G = {};
    return this;
  }
  o.assign = function(key, val) {
    this._G[key] = val;
    return this;
  }
  o.execute = function(tpl, name) {
    if (name == undefined) name = 'default';
    var fn_str = null;
    if (this.fnPool[name] != undefined) fn_str = this.fnPool[name];
    else {
      var reg = /<%=?([^>]+)%>/g;
      var CD = "var C = [];\n";
      var append = function(line) {
        var T = line.replace(/'/g, "\\\'").replace(/[\n\t]{1,}/g, " ");
        CD += "C.push('" + T + "');\n";
      }
      var CUR = 0;
      var CHR = 0;
      var TMP = null;
      var LGC = null;
      var m;
      while ((m = reg.exec(tpl)) != null) {
        append(tpl.slice(CUR, m.index));
        CHR = tpl[m.index + 2];
        LGC = m[1].replace(/\{([a-z0-9_\[\]\.]+)\}/gi, "__G__.$1");
        if (CHR == this.print_prefix) CD += "C.push(" + LGC + ");\n";
        else CD += LGC + "\n";
        CUR = m.index + m[0].length;
      }
      append(tpl.substr(CUR, tpl.length - CUR));
      CD += "return C.join('');\n";
      fn_str = CD;
      this.fnPool[name] = CD;
    }
    var ret = (function(__G__) {
      var r = '';
      try {
        //console.log(fn_str);
        var r = eval('(function(){' + fn_str + '}())');

      } catch(err) {
        console.log(err);
      }
      return r;
    } (this._G));
    return ret;
  }
  o.getParam = function(_name) {
    var pattern = new RegExp("(\\?|#|&)" + _name + "=([^&#]*)");
    var m = window.location.href.match(pattern);
    return (!m ? "": m[2]);
  }
  o.getTimeString = function(o_time, c_time) {
    t = c_time - o_time;
    if (t < 0) {
      var d = new Date();
      d.setTime(o_time * 1000);
      return d.getFullYear() + '年' + (d.getMonth() + 1) + '月' + d.getDate() + '日';
    }
    if (t < 5) return '刚刚';
    if (t < 60) return t + '秒前';
    if (t < 3600) return Math.floor(t / 60) + '分钟前';
    if (t < 86400) return Math.floor(t / 3600) + '小时前';
    if (t < 2592000) return Math.floor(t / 86400) + '天前';
    var d = new Date();
    d.setTime(o_time * 1000);
    if (t < 31104000) {
      return (d.getMonth() + 1) + '月' + d.getDate() + '日';
    }
    return d.getFullYear() + '年' + (d.getMonth() + 1) + '月' + d.getDate() + '日';
  }
  return o;
} ();

(
  function(window) {
    var clientWidth = $(window).width() > 640 ? 640 : $(window).width();
    var clientHeight = $(window).height();
    var gdata = null;
    var questionCount = 0;
    var pageCount = 1;
    var pageNum;
    var answerResult = {};
    var answerIscrollArr = [];
    var coverIscroll = null;
    var resultIscroll = null;
    var touchName = 'ontouchstart' in window ? 'tap': 'click';
    var processVal = 0;
    var processTimeId = null;
    var isWechat = navigator.userAgent.indexOf('MicroMessenger') > -1;

    var queCount = 0;//当前题目
    var options = {
      bgImg: 'img/bg-default.jpg',
      logoImg: '/static/images/logo.default.png',
      //selAnswerBgcolor: 'rgb(215,215,215)',
      unselAnswerBgcolor:'#dbdbdb',
      selAnswerBgcolor: '#1da664',
      nextPageTime: 710,
      nextPageWaitingTime: 500,
      resultImgHeight: 170,
      answerImgWidth: 120,
      answerImgHeight: 80,
      coverDesc: {
        duration: 1000,
        animate: 'zoomIn'
      },
      coverTitle: {
        duration: 1000,
        animate: 'zoomIn' //shake
      },
      coverCoverImg: {
        duration: 0,
        animate: 'fadeInDownBig'
      },
      coverBtn: {
        duration: 1000,
        animate: 'lightSpeedIn'
      },
      mainTitle: {
        duration: 0,
        animate: ''
      },
      mainCoverImg: {
        duration: 0,
        animate: 'zoomInDown'
      },
      mainAnswers: {
        duration: 1000,
        animate: 'fadeInUp'
      },
      resultBox: {
        duration: 100,
        animate: 'slideInDown'
      }
    };

    var myTempHieght = 0;
    var myAnswersHeight = 0;
    function quizInit(data, containerSel, tplSel, opts) {
      try {
        //gdata = eval('(' + yoparentData + ')');
        gdata = window.yoparentData;
      } catch(err) {
        return false;
      }
      data = window.yoparentData;

      _initOptions(opts);
      var tree = _assignDataToTpl(tplSel);
      var contentBox = $(tree).find('[attr-content]');
      var pageBox = $(tree).find('[attr-page]');
      pageNum = pageBox.length;
      contentBox.css({
        width: clientWidth + 'px',
        height: clientHeight * pageBox.length + 'px'
      });
      pageBox.css({
        width: clientWidth + 'px',
        height: clientHeight + 'px'
      });
      $(tree).find('div.img-cover[img-src]').each(function() {
        var that = $(this);
        var curImgWidth = that.attr('img-width'),
          curImgHeight = that.attr('img-height');
        var tempHeight = (curImgHeight / curImgWidth) * clientWidth;
        tempHeight = tempHeight > clientHeight / 2 ? clientHeight / 2 : tempHeight;
        myTempHieght = tempHeight;

        options.resultImgHeight = tempHeight;
        that.css({
          height: tempHeight + 'px'
        });
        that.find('img').css({
          width: '100%',
          height: tempHeight + 'px'
        });
//        that.siblings('[answers-wrapper]').css({
//          height: (clientHeight - tempHeight) - 75 + 'px'
//        });
//        console.log((clientHeight - tempHeight) - 75 + 'px');

        //that.parent().find
        //that.parent().find('[main-answers]').css({
        //  height: (clientHeight - tempHeight) + 'px'
        //});

        //add by tian 按比例设置title的top值;
        that.siblings('[cover-title]').css({
          top: tempHeight*60/100 - 30
        });
      });

      $(tree).find('div.img-wrap[img-src]').each(function() {
        var that = $(this);
        try {
          var layout = JSON.parse(that.attr('data-layout'));
          var imgWrapWidth = (
              parseInt(clientWidth) -
              ((parseInt(layout.cols) + 1) * 8) -
              (parseInt(layout.cols) * 12)
            ) / parseInt(layout.cols);
          options.answerImgWidth = imgWrapWidth;
        } catch(e) {}
        var curImgWidth = that.attr('img-width'),
          curImgHeight = that.attr('img-height'),
          tempHeight = (curImgHeight / curImgWidth) * options.answerImgWidth;
        if (clientWidth > 500) {
          options.answerImgHeight = 150;
        }
        tempHeight = tempHeight > options.answerImgHeight ? options.answerImgHeight: tempHeight;

        that.css({
          width: options.answerImgWidth + 'px',
          height: tempHeight + 'px'
        });
//        if (that.parent('li.hr[answer-item]').find('.pl').length !== 0) {
//          that.parent('li.hr[answer-item]').css({
//            'padding-left': options.answerImgWidth + 5 + 10 + 'px',
//            'min-height': tempHeight + 16 + 'px'
//          });
//        } else {
//          that.parent('li.hr[answer-item]').css({
//            'padding-right': options.answerImgWidth + 5 + 10 + 'px',
//            'min-height': tempHeight + 16 + 'px'
//          });
//        }

      });


      $(containerSel).append($(tree).children().get(0));
      var containerElment = $(containerSel);
      var pageElment = containerElment.find('[attr-page]');
      _initIscroll(containerElment);
      _initBgCoverImg(containerElment);
      _loadImg($(pageElment[pageCount]).find('div[img-src]'),
        function(obj) {
          var temp = $(obj).attr('style') + 'background:url(' + $(obj).attr('img-src') + ') top center no-repeat;background-size: 100% auto;background-origin:content-box;';
          $(obj).attr('style', temp);
        });

   _event(containerElment, pageElment);
      if (isWechat) {
        var script = document.createElement('script');
        script.type = 'text/javascript';
        script.src = '/util/wechat/shr?v=' + Math.random();
        document.body.appendChild(script);
      }

    }
    function _event(containerElment, pageElment) {
      var content = containerElment.find('[attr-content]');

      $('#start').bind(touchName,
        function() {
          pageCount++;
          _nextPage(content, _getSliderHeight(clientHeight), pageElment);
          _loadImg($(pageElment[pageCount]).find('div[img-src]'),
            function(obj) {
              var temp = $(obj).attr('style') + 'background:url(' + $(obj).attr('img-src') + ') top center no-repeat;background-size: 100% auto;background-origin:content-box;';
              $(obj).attr('style', temp);
            });
        });



      //added by tian
      $('.continue').bind(touchName,
      function() {
        //检查数据是否已经有了
        //if(!answerResult[pageCount - 1]){
        //  return;
        //}

        //判断是否已经高亮
        if(!$(this).hasClass('highLight')){
          return;
        }


          $that = $(this);
          if ($that.attr('disable') && $that.attr('disable') !== "0") {
            return;
          }
          $that.attr('disable',"1");

          //得到该页面的选择结果
          var answersSwapper = $that.parent().parent().find("[answer-item]");
          var userSelect = [];
          var qid = -1;
          _.each(answersSwapper,function(one){
            var $one = $(one);
            qid = $one.attr('qid');
            if($one.attr('disable') === '1'){
              userSelect.push($one.attr('id'));
            }
          });

          var nextPageDesc;
          if(userSelect.length > 0){
            roundDataUtil.selectItem(qid, userSelect);
            //得到下一页的参数
            nextPageDesc = roundDataUtil.getNext(userSelect[0]);
          }else{
            nextPageDesc = roundDataUtil.getNext(null);
          }
          // 如果是type是r，则掉转到结果页面
          // 否则渲染下一页


          //已经填满,这时进行翻页操作
          $that.parent().parent().find('[answer-item]').attr('disable', 1);
          //answerAction($that);

          if(nextPageDesc.type === 'q'){
            //更新下一页数据
            $nextPage = $(pageElment[pageCount]);
            $captionBg = $nextPage.find('[main-img]');
            $captionBg.attr('img-src', nextPageDesc.data.img_src);
            console.log(nextPageDesc.data.img_src);

            //背景图
            var img = new Image();
            img.src = nextPageDesc.data.img_src;
            img.onload = function() {
              var temp = $captionBg.attr('style') + 'background:url(' + nextPageDesc.data.img_src + ') top center no-repeat;background-size: 100% auto;background-origin:content-box;';
              $captionBg.attr('style', temp);
            };
            //标题
            $nextPage.find('.questionIndex').html(nextPageDesc.pageIndex + 1);
            $nextPage.find('.caption').html(nextPageDesc.data.caption);
            //选项
            var answerItems = $nextPage.find('[answer-item]');
            $(answerItems[0]).attr('id', nextPageDesc.data.answers[0].id).html(nextPageDesc.data.answers[0].caption);
            $(answerItems[1]).attr('id', nextPageDesc.data.answers[1].id).html(nextPageDesc.data.answers[1].caption);

            pageCount++;
            setTimeout(function() {
                _nextPage(content, _getSliderHeight(clientHeight), pageElment);
              },
              options.nextPageWaitingTime);
          }else{
            quizResult(nextPageDesc);

            setTimeout(function() {
                _nextPage(content, -(clientHeight*(yoparentData.questions.length + 1)), pageElment);//直接移动到最后一页
              },
              options.nextPageWaitingTime);
          }




          //_loadImg($(pageElment[pageCount]).find('div[img-src]'),
          //  function(obj) {
          //    var temp = $(obj).attr('style') + 'background:url(' + nextPageDesc.data.img_src + ') top center no-repeat;background-size: 100% auto;background-origin:content-box;';
          //    $(obj).attr('style', temp);
          //  });



          //pageCount++;
          //_nextPage(content, _getSliderHeight(clientHeight), pageElment);
          //_loadImg($(pageElment[pageCount]).find('div[img-src]'),
          //  function(obj) {
          //    var temp = $(obj).attr('style') + 'background:url(' + $(obj).attr('img-src') + ') top center no-repeat;background-size: 100% auto;background-origin:content-box;';
          //    $(obj).attr('style', temp);
          //  });
          //
          //if (pageCount >= pageNum) {
          //  quizResult(containerElment);
          //}
        });



      content.bind('touchstart',
        function() {});
      content.bind('touchmove',
        function(event) {
          event.preventDefault();
        });
      content.bind('touchend',
        function() {});

      content.find('[answer-item]').bind(touchName,
        function() {
          var $that = $(this);

          //单选题样式
          if(yoparentData.qType === 'single-choice'){
            $that.parent().find('li').each(function(){
              unhighlightSelect($(this));
              $(this).attr('disable', '0');
            });
            highlightSelect($that);
            $that.attr('disable', '1');
          }else if(yoparentData.qType === 'multiple-choice'){
            if($that.attr('disable') !== "0"){
                unhighlightSelect($that);
                $that.attr('disable', '0');
            }else{
              highlightSelect($that);
               $that.attr('disable', '1');
            }
          }

          var hasHighlight = false;
          $that.parent().find('[answer-item]').each(function(){
            if($(this).attr('disable') !== "0"){

              checkCouldNextPage($that.parent().parent().parent().find('.continue'));
              hasHighlight = true;
            }
          });

//          如果下一页按钮没有高亮，则进行高亮
          if(!hasHighlight){
            couldNotNextPage($that.parent().parent().parent().find('.continue'));
          }

          // if ($that.attr('disable') !== "0") {
          //   $that.attr('disable', '0');
          //   //从该题目已选数据列表中清理
          //   clearCurrentSelect($that);
          //   //判断下一题按钮的高亮
          //   checkCouldNextPage($that);
          //   //清理已高亮的选项
          //   unhighlightSelect($that);

          //   return;
          // }

          // $that.attr('disable', 1);//屏蔽掉现在的选项

          //高亮当前选项
          //highlightSelect($that.find('img'));

          //插入当前的选项
          //answerResult[pageCount - 1] = {
          //  aid: $that.attr('id'),
          //  select:JSON.parse($that.attr('data-results'))
          //};
          //console.log(answerResult);
          //判断下一题按钮的高亮
//          checkCouldNextPage($that);

        });
      // $('#restart').bind(touchName,

      //     function() {
      //         location.href = 'http://weixin.qq.com/r/OUzUzH-EzCKzrTuv9xkr';
      //     });
      $('#share').bind(touchName,
        function() {
          $('.ending').removeClass('hide').addClass('show').addClass('animated').addClass('fadeIn');
          //$('.ending').removeClass('show').removeClass('fadeIn').addClass('fadeOut');
          //setTimeout(function() {
          //    $('.ending').removeClass('show').removeClass('fadeIn').addClass('fadeOut');
          //    $('.ending').addClass('hide').removeClass('fadeOut');
          //    //setTimeout(function() {
          //    //    $('.ending').addClass('hide').removeClass('fadeOut');
          //    //  },
          //    //  1000);
          //  },
          //  1500);
        });

      $('.one-demo-image-wrapper').on(touchName, function(){

          var $that = $(this);
          //如果选择的是已经选择过的,则进行撤消操作
          if ($that.attr('disable') !== "0") {
            $that.attr('disable', '0');
            //从该题目已选数据列表中清理
            clearCurrentSelect($that);
            //判断下一题按钮的高亮
            checkCouldNextPage($that);
            //清理已高亮的选项
            unhighlightSelect($that);

            return;
          }

          if(!checkCouldInsertSelect()){
            return;
          }

          $that.attr('disable', 1);//屏蔽掉现在的选项

          //高亮当前选项
          highlightSelect($that);

          //插入当前的选项
          var curQuestionAnswerSize = insertCurrentSelect($that);
          //判断下一题按钮的高亮
          checkCouldNextPage($that);

          // console.log( answerResult[pageCount - 2]);
    });

      $(window).bind('load',
        function() {
          _orientationChange();
          window.onorientationchange = _orientationChange;
        });
    }
    function quizResult(resultPageDesc) {
      //客户端实现计算结果的罗辑
      //showResult();

      var psTime = (new Date()).getTime();
      $.post(window.resultUrl, {
          token: window.yoparentToken,
          createTime: window.yoparentStartTime,
          result: JSON.stringify(roundDataUtil.getUserSelectResult()),
          quizId: window.yoparentData.id
        },
        function(ret) {
          if (ret === null) {
            window.alert('服务器错误，请稍后重试！');
            return;
          }
          if (ret.status === false) {
            window.location.reload();
            return;
          }
          //var resultPageDesc = window.roundDataUtil.getNext(answerResult[pageCount - 1], answerResult);

          var curTime = (new Date()).getTime();
          var deltaTime = curTime - psTime;
          deltaTime = deltaTime < 1500 ? 1500 : deltaTime;
          deltaTime = deltaTime > 2000 ? 0 : deltaTime;
          setTimeout(function() {
              showResult(resultPageDesc);
            },
            deltaTime);
        });
    }
    function showResult(ret) {
      var resultBox = $('.result-box');
      setTimeout(function() {
          var rimgWidth = (750 / 500) * options.resultImgHeight;
          if (rimgWidth > clientWidth) {
            rimgWidth = clientWidth;
          }

//          ret = JSON.parse(ret);
//          ret.data.rate = JSON.parse(ret.data.rate);
          var resultDesc = {
            data:ret
          }

          //计算分享的文字
          var descTemplate = _.template($('#share-description-tpl').html());
          var tempDesc = descTemplate(resultDesc);

          console.log(tempDesc);

          if ( !! window.wxReady) {
            window.yoparentWxConfig.title = trim(tempDesc);
            window.yoparentWxTimeineConfig.title = trim(tempDesc);
            window.yoparentWxConfig.imgUrl = ret.data.url;
            window.yoparentWxTimeineConfig.imgUrl = ret.data.url;
            window.wx.onMenuShareTimeline(window.yoparentWxTimeineConfig);
            window.wx.onMenuShareAppMessage(window.yoparentWxConfig);
          }
          setTimeout(function(){
            new IScroll(document.querySelector('#result-wrapper'), {
              mouseWheel: true,
              tap: false,
              scrollbars: true,
              fadeScrollbars: true,
              interactiveScrollbars: false
            });

          },500);

          var resultDescTemplate = _.template($('#result-tpl').html());

          $($('#result-wrapper li')[1]).html(resultDescTemplate(resultDesc));
          resultBox.removeClass('hide').addClass('show').addClass('animated').addClass(options.resultBox.animate);
          $('.result-wrapper').css({
            height: clientHeight - 142 + 'px'
          });
        },
        options.resultBox.duration);

    }

    function highlightSelect(obj){
      var colorV = options.selAnswerBgcolor;
      obj.css({
        //'background-color': colorV
        'border-style': 'solid',
        'border-width': '4px',
        'border-color':'rgb(178, 237, 56)'
      });
    }
    function unhighlightSelect(obj){

      obj.css({
        'border-style': 'solid',
        'border-width': '4px',
        'border-color':'#dbdbdb'
      });
    }

    function checkCouldInsertSelect(){
      var curPageCount = pageCount-2;
      var arrLength = 1;
      if(curPageCount === 0 ){
          arrLength = 5
      }else{
        if(!answerResult[curPageCount]){
          return true;
        }else{
          return false;
        }
      }

      var tempAnswerArr = answerResult[curPageCount];
      if(!!tempAnswerArr && tempAnswerArr.length === arrLength){
        return false;
      }
      return true;
    }

    function insertCurrentSelect(obj) {
      var dataResults = obj.attr('data-results');
      if (!dataResults) {
        return;
      }

      var tempAnswerArr = answerResult[pageCount - 2];
      if (!tempAnswerArr) {
        tempAnswerArr = [];
      }

      tempAnswerArr.push(dataResults);
      answerResult[pageCount - 2] = tempAnswerArr;

      return tempAnswerArr.length;
    }
    function clearCurrentSelect(obj) {
      var dataResults = obj.attr('data-results');
      if (!dataResults) {
        return;
      }

      var tempAnswerArr = answerResult[pageCount - 2];
      var index = _.indexOf(tempAnswerArr, dataResults);
      tempAnswerArr.splice(index, 1);

      return tempAnswerArr.length;
    }
    function checkCouldNextPage($btn){
      $btn.addClass('highLight');
      //$btn.css({
      //  'color': '#b2ed38'
      //});
    }
    function couldNotNextPage($btn){
      $btn.removeClass('highLight');
    }

    function answerAction(obj) {
      queCount++;
    }
    function _getSliderHeight(clientHeight) {
      return - (clientHeight + clientHeight * (pageCount - 2));
    }

    var hasRedawed = false;
    var drawDataCount = 0;
    var oneSceneTemp;


    function _nextPage(content, dist, pageElment) {
      if (!content) {
        return;
      }

      setTimeout(function(){
        var answersWrapper = $('.my-page-wrapper');

        for (var i = 0; i < answersWrapper.length; i++) {
          new IScroll(answersWrapper[i], {
            mouseWheel: true,
            tap: false,
            scrollbars: true,
            fadeScrollbars: true,
            interactiveScrollbars: false
          });
        }

      },2000);


      var oldPage = $(pageElment[pageCount - 2]);
      if(!!oldPage){
        oldPage.css({
          'visibility': 'hidden'
        });
      }

      var curPage = $(pageElment[pageCount - 1]);
      content.addClass('transition');
      content.css('-webkit-transform', 'translate(0,' + dist + 'px)');
      content.css('transform', 'translate(0,' + dist + 'px)');
      if (pageCount >= pageNum){
        return;
      }

      var tmpNextPageTime = options.nextPageTime;
//      console.log(tmpNextPageTime);
      setTimeout(function() {
          content.removeClass('transition');
          setTimeout(function() {
              var tt = curPage.find('[main-img]').removeClass('hide').addClass('show');
              if(tmpNextPageTime !== 0){
                tt.addClass('animated').addClass(options.mainCoverImg.animate);
              }
            },
            options.mainCoverImg.duration);
          setTimeout(function() {
              curPage.find('[main-title]').removeClass('hide').addClass('show').addClass('animated').addClass(options.mainTitle.animate);
            },
            options.mainTitle.duration);
          setTimeout(function() {
              curPage.find('[answers-wrapper]').removeClass('hide').addClass('show').addClass('animated').addClass(options.mainAnswers.animate);
              var li = curPage.find('[main-answers] > li');
              li.each(function() {
                //$(this).find('[answer-item]').height($(this).height());
              });
              // answerIscrollArr[pageCount - 2].refresh();
            },
            options.mainAnswers.duration);

            setTimeout(function(){
              curPage.find('.continue-btn-wrap').show();
            },500);
        },
        tmpNextPageTime);
    }
    function _initIscroll(containerElment) {
      containerElment.find('#cover-scroller').css({
        height: clientHeight - (49 + 50 + containerElment.find('[cover-img]').height() + 15) + 'px'
      });
      //containerElment.find('[cover-wrapper]').css({
      //  height: clientHeight - (49 + 50 + containerElment.find('[cover-img]').height() + 15) + 'px'
      //});
      //coverIscroll = new IScroll(document.querySelector('[cover-wrapper]'), {
      //  mouseWheel: true,
      //  tap: false,
      //  scrollbars: true,
      //  fadeScrollbars: true,*2
      //  interactiveScrollbars: false
      //});
//      var answersWrapper = containerElment.find('[my-page-wrapper]');
//
//      for (var i = 0; i < answersWrapper.length; i++) {
//        var temp = new IScroll(answersWrapper[i], {
//          mouseWheel: true,
//          tap: false,
//          scrollbars: true,
//          fadeScrollbars: true,
//          interactiveScrollbars: false
//        });
//        answerIscrollArr.push(temp);
//      }


      //added by tian
      $('.question_explain_content_wrapper').css({
        //height: clientHeight - (50 + 113 + 40 + 15 + 15 + options.resultImgHeight) + 'px'
        height: clientHeight - ( 70 +  20 + options.resultImgHeight) + 'px'
      });
      //var explainDescWrapper = $('[explain-desc-wrapper]');
      //for (var i = 0; i < explainDescWrapper.length; i++) {
      //  var temp = new IScroll(explainDescWrapper[i], {
      //    mouseWheel: true,
      //    tap: false,
      //    scrollbars: true,
      //    fadeScrollbars: true,
      //    interactiveScrollbars: false
      //  });
      //}
    }
    function _coverAnimate(containerElment) {
      var cover = containerElment.find('[attr-cover]');
      var h1 = cover.find('[cover-title]'),
        img = cover.find('[cover-img] > img'),
        desc = cover.find('[cover-desc]'),
        start = $('[cover-btn]');
      setTimeout(function() {
          img.removeClass('hide').addClass('show').addClass('animated').addClass(options.coverCoverImg.animate);
        },
        options.coverCoverImg.duration);
      setTimeout(function() {
          h1.removeClass('hide').addClass('show').addClass('animated').addClass(options.coverTitle.animate);
        },
        options.coverTitle.duration);
      setTimeout(function() {
          desc.removeClass('hide').addClass('show').addClass('animated').addClass(options.coverDesc.animate);
        },
        options.coverDesc.duration);
      setTimeout(function() {
          start.removeClass('hide').addClass('show').addClass('animated').addClass(options.coverBtn.animate);
        },
        options.coverBtn.duration);
      setTimeout(function() {
          //coverIscroll.refresh();


          //coverIscroll = new IScroll(document.querySelector('[cover-wrapper]'), {
          coverIscroll = new IScroll($('#cover-scroller')[0], {
            mouseWheel: true,
            tap: false,
            scrollbars: true,
            fadeScrollbars: true,
            interactiveScrollbars: false
          });
        },
        1000);
    }
    function _initBgCoverImg(containerElment) {
      _loadCoverImg(containerElment.find('[cover-img]'),
        function(imgSrc, obj) {
          var imgObj = $(obj).find('img');
          imgObj.css({
            width: 100 + '%',
            height: 'atuo'
          });
          imgObj.attr('src', imgSrc);
        });


      _coverAnimate(containerElment);
    }
    function _loadBgImg(bgSrc, callback) {
      var img = new Image();
      img.src = bgSrc;
      img.onload = function() {



        callback(img.src);
      };
    }
    function _loadLogoImg(logoSrc, callback) {
      var img = new Image();
      img.src = logoSrc;
      img.onload = function() {
        callback(img.src);
      };
    }
    function _loadingImg(obj, callback) {
      var img = new Image();
      img.src = $(obj).attr('img-src');
      img.onload = function() {
        callback(obj);
      };
    }
    function _loadImg(imgsObj, callback) {
      if (typeof imgsObj === 'undefined' || imgsObj === null) {
        return;
      }
      for (var i = 0; i < imgsObj.length; i++) {
        _loadingImg(imgsObj[i], callback);
      }
    }
    function _loadCoverImg(obj, callback) {
      var img = new Image();
      img.src = $(obj).attr('img-src');
      img.onload = function() {
       callback(img.src, obj);
      };
    }
    function _initOptions(opts) {
      for (var val in opts) {
        if (typeof opts[val] === 'object') {
          for (var obj in opts[val]) {
            options[val][obj] = opts[val][obj];
          }
        } else {
          options[val] = opts[val];
        }
      }
    }
    function _assignDataToTpl(tplSel) {
      var posterTpl = $(tplSel).html();
      var compiled = _.template(posterTpl);
      var HTML = compiled(
        {
          'title' : gdata.title,
          'img_src': gdata.imgSrc,
          'description': gdata.description,
          'imgWidth': gdata.imgWidth,
          'imgHeight': gdata.imgHeight,
          'questions': gdata.questions
        }

      );
      var tree = document.createElement('div');
      tree.innerHTML = HTML;
      return tree;
    }
    var orientationFlags = false;
    function _orientationChange() {
      switch (window.orientation) {
        case 0:
          if (orientationFlags) {
            location.reload();
            orientationFlags = false;
          }
          break;
        case - 90 : if (!orientationFlags) {
          $('.orientation').removeClass('hide').add('show');
          orientationFlags = true;
        }
          break;
        case 90:
          if (!orientationFlags) {
            $('.orientation').removeClass('hide').add('show');
            orientationFlags = true;
          }
          break;
        case 180:
          if (orientationFlags) {
            location.reload();
            orientationFlags = false;
          }
          break;
      }
    }
    window.WeittQuiz = {
      run: quizInit
    };
  })(window);
